#include "gd32f3x0.h"
#include <stdio.h>
#include <string.h>
#include "gd32f310k_start.h"
#include "systick.h"
#include "bsp_usart.h"
#include "bsp_led.h"

extern uint8_t rxbuffer[RX_BUFFER_MAX];
extern uint8_t txbuffer[TX_BUFFER_MAX];
typedef enum{
	e_min=-1,
	e_init=0,
	e_at_ok,
	e_wifi_ok,
	e_sock_ok,
	e_connect_ok,
	e_max
}e_at_state;
uint8_t led_counter = 0;

void led_ind(e_at_state at_state)
{
	switch(at_state)
	{
		case e_at_ok:
		case e_wifi_ok:
		case e_sock_ok:
			if(led_counter == 10)
			{
				led_toggle();
				led_counter = 0;
			}
			else
			{
				led_counter++;
			}
		break;
		case e_connect_ok:
			if(led_counter == 5)
			{
				led_toggle();
				led_counter = 0;
			}
			else
			{
				led_counter++;
			}
		break;
		default:
			printf("get into other:%d\n", at_state);
		break;
	}
	
}
uint8_t sat(char *cmd, char *expectRsp)
{
	uint8_t ret = 0;
	char req[128] = {0};
	uint8_t rsp[128] = {0};
	sprintf(req,"%s\r\n",cmd);
	usart_dma_send(USART0,(uint8_t *)req, strlen(req));
	//delay_1ms(100);
	usart_dma_recv(USART0, rsp, sizeof(rsp));
	if(NULL != strstr((char *)rxbuffer, expectRsp))
	{
		ret = 0;
	}
	else
	{
		ret = 1;
	}

	return ret;
}
uint8_t wait_atrsp(char *rsp)
{
	uint8_t ret = 0;
	uint8_t recv_len = 0;
	if(rsp == NULL)
	{
		return ret;
	}
	recv_len = usart_dma_recv(USART0, (uint8_t *)rsp, 128);
	
	ret = recv_len;
	return ret;
}
int main(void)
{
		e_at_state at_state = e_init;
    /* enable DMA clock */
    rcu_periph_clock_enable(RCU_DMA);
	
    /* initilize the com */
    usart0_gpio_config();
    usart0_config();

    //printf("\n\ra usart dma function test example!\n\r");
		//printf("\r\nsend test OK\r\n");

    while(1) {
			switch (at_state)
			{
				case e_init:
					sat("AT", "OK");
					at_state = e_wifi_ok;
				break;
				case e_at_ok:
					
					at_state = e_wifi_ok;
				break;
				case e_wifi_ok:
					at_state = e_sock_ok;
				break;
				case e_sock_ok:
					at_state = e_connect_ok;
				break;
				case e_connect_ok:
				{
					char at_resp[128] = {0};
					wait_atrsp(at_resp);
					printf("at_resp:%s\r\n", at_resp);
				}
				break;
				default:
					printf("Get into other:%d\n",at_state);
				break;
			}
			usart_dma_recv(USART0, rxbuffer, sizeof(rxbuffer));
			led_ind(at_state);
			delay_1ms(100);
    }
}


/* retarget the C library printf function to the USART */
int fputc(int ch, FILE *f)
{
    usart_data_transmit(USART0, (uint8_t) ch);
    while(RESET == usart_flag_get(USART0, USART_FLAG_TBE));
    return ch;
}

